<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/14 0014
 * Time: 8:59
 */

namespace app\data\controller;


use think\Db;

class Heyue extends Base
{
    public function HeYueActualData(){
      	$date = date('Hi',time());
      	if($date > '0000'  && $date < '0020')return false;
        $map = ['a.type'=>2,'a.pid'=>['>',0]];
        $list  = Db::name('currency')
            ->alias('a')
            ->join('currency b','a.pid=b.cu_id')
            ->where($map)
            ->field('a.cu_id,a.title,b.title as platform')
            ->select();
        $SystemPrice = Db::name('heyue_data')->select();
        foreach ($list as $k=>$v){
            switch ($v['platform']){
                case 'OKEx';
                    $num = json_decode($this->cUrl('https://www.okex.com/api/futures/v3/instruments'));
                    foreach ($num as $ke=>$va){
                        if($va->underlying_index != strtoupper($v['title']))continue;
                        if($va->alias == 'this_week'){
                            $num = str_replace(['2019','-'],['19',''],$va->delivery);
                            $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$num.'/candles?granularity=60';
                            $data = json_decode($this->cUrl($api));                          	
                            if(!isset($data))continue;
                            $price =[
                                'price'=>$data[0][4],
                                'platform'  =>'OKEx',
                                'title'     =>$v['title'],
                            ];
                            Db::name('heyue_data')->where(['title'=>$v['title'],'platform'=>'OKEx','time'=>1])->update(['nowprice'=>$data[0][4]]);
                          	$msg =  $this->ContrastSystem($SystemPrice,$price,'当周');        
                            if(!$msg)continue;    	
                            $map = ['cu_id'=>$v['cu_id'],'time'=>1,$msg['type']=>0];
                            $user = Db::name('heyue_user')->where($map)->column('uid');                          	
                            if(!$user)continue;
                            $a= $this->SendMsg($msg,$user,6);
                          	Db::name('heyue_user')->where(['uid'=>['in',$user],'time'=>1,'cu_id'=>$v['cu_id']])->update([$msg['type']=>1]);
                            $reg_id = $this->GetPushReg($user);
                            if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);
                        }
                        if($va->alias == 'next_week'){
                            $num = str_replace(['2019','-'],['19',''],$va->delivery);
                            $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$num.'/candles?granularity=60';
                            $data = json_decode($this->cUrl($api));  	
                            if(!isset($data))continue;
                            $price =[
                                'price'=>$data[0][4],
                                'platform'  =>'OKEx',
                                'title'     =>$v['title'],
                            ];
                            Db::name('heyue_data')->where(['title'=>$v['title'],'platform'=>'OKEx','time'=>2])->update(['nowprice'=>$data[0][4]]);
                          	$msg =  $this->ContrastSystem($SystemPrice,$price,'次周');
                            if(!$msg)continue;
                            $map = ['cu_id'=>$v['cu_id'],'time'=>2,$msg['type']=>0];                          	
                            $user = Db::name('heyue_user')->where($map)->column('uid');
                            if(!$user)continue;                            
                          	$rese =  Db::name('heyue_user')->where(['uid'=>['in',$user],'time'=>2,'cu_id'=>$v['cu_id']])->update([$msg['type']=>1]);
                            $this->SendMsg($msg,$user,6);
                            $reg_id = $this->GetPushReg($user);
                            if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);
                        }
                        if($va->alias == 'quarter'){
                            $num = str_replace(['2019','-'],['19',''],$va->delivery);
                            $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$num.'/candles?granularity=60';
                            $data = json_decode($this->cUrl($api));
                            if(!isset($data))continue;
                            $price =[
                                'price'=>$data[0][4],
                                'platform'  =>'OKEx',
                                'title'     =>$v['title'],
                            ];
                            Db::name('heyue_data')->where(['title'=>$v['title'],'platform'=>'OKEx','time'=>3])->update(['nowprice'=>$data[0][4]]);
                          	$msg =  $this->ContrastSystem($SystemPrice,$price,'季度');
                          	if(!$msg)continue;                         	
                            $map = ['cu_id'=>$v['cu_id'],'time'=>3,$msg['type']=>0];
                            $user = Db::name('heyue_user')->where($map)->column('uid');
                            if(!$user)continue;                                                                                
                          	Db::name('heyue_user')->where(['uid'=>['in',$user],'time'=>3,'cu_id'=>$v['cu_id']])->update([$msg['type']=>1]);
                            $this->SendMsg($msg,$user,6);
                            $reg_id = $this->GetPushReg($user);
                            if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);
                        }
                    }
                    break;
                case 'Huobi';
                    $this->HuoBi(1,$v['title'],$v['cu_id'],$SystemPrice);
                    $this->HuoBi(2,$v['title'],$v['cu_id'],$SystemPrice);
                    $this->HuoBi(3,$v['title'],$v['cu_id'],$SystemPrice);
                    break;
            }
        }
        return;
    }

    private function HuoBi($time,$title,$cu_id,$SystemPrice){
        switch ($time){
            case 1;
                $lib = "CW";
                $ref = '当周';
                break;
            case 2;
                $lib = "NW";
                $ref = '次周';
                break;
            case 3;
                $lib = "CQ";
                $ref = '季度';
                break;
        }
        $api = "https://api.hbdm.com/market/history/kline?symbol=".strtoupper($title)."_".$lib."&period=1min&size=1";
        $data = json_decode($this->cUrl($api));
        if(!isset($data->data))return;
        $resf = Db::name('heyue_data')->where(['title'=>$title,'platform'=>'Huobi','time'=>$time])->update(['nowprice'=>$data->data[0]->close]);
      	$msg = $this->ContrastSystem($SystemPrice,$data->data[0]->close,$ref); 	
        if(!$msg)return;
      	var_dump($msg);
        $user = Db::name('heyue_user')
            ->join('user_service b','a.uid=b.uid')
            ->where(['b.expire'=>['notBetween',[1,time()]],'b.vip'=>['>',0]])
            ->where(['a.cu_id'=>$cu_id,'a.time'=>$time,'a.'.$msg['type']=>0])
            ->column('a.uid');
        if(!$user)return;
        $price = ['price'=>$data->data[0]->close,'platform'=>"Huobi",'title'=>$title];       
      	Db::name('height_remind')->where(['uid'=>['in',$user],'time'=>$time])->update([$msg['type']=>1]);
        $this->SendMsg($msg,$user,6);
        $reg_id = $this->GetPushReg($user);
        if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);
    }


    private function ContrastSystem($system,$price,$time){
      	if($time == '当周')$re = 1;
      	if($time == '次周')$re = 2;
      	if($time == '季度')$re = 3;
        $message = Db::name('message_model')->where(['type'=>5])->field('content,title')->select();
        $s3m = $message[0];$s2m = $message[1];$s1m = $message[2];$b3m = $message[3];$b2m = $message[4];$b1m = $message[5];
        $x = Db::name('price_set')->where(['id'=>2])->value('x');
        foreach ($system as $k=>$v){
            if($v['platform'] == $price['platform'] && $v['title'] == $price['title'] && $v['time'] == $re){              	
                $ref = ['platform'=>$v['platform'],'title'=>$v['title'],'time'=>$time];
                if($price['price'] <= $v['buy_3']){
                  	$type = 'b3';
                    $ref['buy_3'] = $v['buy_3'];
                    $content = $b3m['content'];
                    $title = $b3m['title'];
                }elseif($price['price'] <= $v['buy_2']){
                  	$type = 'b2';
                    $ref['buy_2'] = $v['buy_2'];
                    $content = $b2m['content'];
                    $title = $b2m['title'];
                }elseif($price['price'] <= $v['buy_1']){
                  	$type = 'b1';
                    $ref['buy_1'] = $v['buy_1'];
                    $content = $b1m['content'];
                    $title =   $b1m['title'];
                }elseif($price['price'] >= $v['sell_3']){
                  	$type = 's3';
                    $ref['sell_3'] = $v['sell_3'];
                    $content = $s3m['content'];
                    $title = $s3m['title'];
                }elseif($price['price'] >= $v['sell_2']){
                  	$type = 's2';
                    $ref['sell_2'] = $v['sell_2'];
                    $content = $s2m['content'];
                    $title = $s2m['title'];
                }elseif($price['price'] >= $v['sell_1']){
                  	$type = 's1';
                    $ref['sell_1'] = $v['sell_1'];
                    $content = $s1m['content'];
                    $title = $s1m['title'];
                }else{
                    return false;
                }
                $tip = $this->GetMessage($content,$title,$ref);
              	$tip['type'] = $type;
                return $tip;
            }
        }
    }
  
  
  
    public function GetHeYueData(){
        $map = ['a.type'=>2,'a.pid'=>['>',0]];
        $list  = Db::name('currency')
            ->alias('a')
            ->join('currency b','a.pid=b.cu_id')
            ->where($map)
            ->field('a.cu_id,a.title,b.title as platform')
            ->select();
        try{
            Db::startTrans();
            $message = Db::name('message_model')->where(['id'=>2])->field('content,title')->find();
           // $re = ['b1'=>0,'b2'=>0,'b3'=>0,'s1'=>0,'s2'=>0,'s3'=>0];
           // Db::name('heyue_user')->where(['uid'=>['<',999999]])->update($re);
            foreach ($list as $k=>$v){
                switch ($v['platform']){
                    case 'OKEx';
                        $num = json_decode($this->cUrl('https://www.okex.com/api/futures/v3/instruments/'));
                        foreach ($num as $ke=>$va){
                            if($va->underlying_index != strtoupper($v['title']))continue;
                            if($va->alias == 'this_week'){
                                $this_week_num = str_replace(['2019','-'],['19',''],$va->delivery);
                                $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$this_week_num.'/candles?granularity=86400';
                                $data = json_decode($this->cUrl($api));
                                if(isset($data)){
                                    $this_week_price = [
                                        'price' =>$data[1][4],
                                        'platform'=>$v['platform'],
                                        'title' =>$v['title'],
                                        'cu_id'	=>$v['cu_id'],
                                    ];
                                    $b = $this->tran($this_week_price['price'],$v['platform'],$v['title'],1,$v['cu_id']);
                                    $b['time'] = '当周';
                                    $this->HeYueNext($b,$v['cu_id'],$message,1);
                                }
                            }
                            if($va->alias == 'next_week'){
                                $next_week_num = str_replace(['2019','-'],['19',''],$va->delivery);
                                $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$next_week_num.'/candles?granularity=86400';
                                $data = json_decode($this->cUrl($api));
                              	
                                if(isset($data)){
                                    $next_week_price = [
                                        'price' =>$data[1][4],
                                        'platform'=>$v['platform'],
                                        'title' =>$v['title'],
                                        'cu_id'	=>$v['cu_id'],
                                    ];
                                    $b = $this->tran($next_week_price['price'],$v['platform'],$v['title'],2,$v['cu_id']);
                                    $b['time'] = '次周';
                                    $this->HeYueNext($b,$v['cu_id'],$message,2);
                                  
                                }

                            }
                            if($va->alias == 'quarter'){
                                $quarter_num = str_replace(['2019','-'],['19',''],$va->delivery);
                                $api = 'https://www.okex.com/api/futures/v3/instruments/'.strtoupper($v['title']).'-USD-'.$quarter_num.'/candles?granularity=86400';
                                $data = json_decode($this->cUrl($api));
                                if(isset($data)){
                                    $quarter_price = [
                                        'price' =>$data[1][4],
                                        'platform'=>$v['platform'],
                                        'title' =>$v['title'],
                                        'cu_id'	=>$v['cu_id'],
                                    ];
                                    $b = $this->tran($quarter_price['price'],$v['platform'],$v['title'],3,$v['cu_id']);
                                    $b['time'] = '季度';
                                    $this->HeYueNext($b,$v['cu_id'],$message,3);
                                }
                            }
                        }
                        break;
                    case 'Huobi';
                        $CWdata = $this->HuoBiGetData(1,$v['title'],$v['cu_id'],$message);
                        $NWdata = $this->HuoBiGetData(2,$v['title'],$v['cu_id'],$message);
                        $CQdata = $this->HuoBiGetData(3,$v['title'],$v['cu_id'],$message);
                }
            }
            Db::commit();
            return 1; 
        }catch (\Exception $e){
            Db::rollback();
            $this->GetHeYueData();
        }
    }
    //todo 火币拉取数据
    private function HuoBiGetData($time,$title,$cu_id,$message){
        switch ($time){
            case 1;
                $lib = "CW";
                $ref = '当周';
                break;
            case 2;
                $lib = "NW";
                $ref = '次周';
                break;
            case 3;
                $lib = "CQ";
                $ref = '季度';
                break;
        }
        $api = "https://api.hbdm.com/market/history/kline?symbol=".strtoupper($title)."_".$lib."&period=1day&size=2";      	
        $data = json_decode($this->cUrl($api));
      	//var_dump($data);die;
        if(!isset($data->data))return;
        $b = $this->tran($data->data[0]->close,'Huobi',$title,$time,$cu_id);
        $b['time'] = $ref;
        $this->HeYueNext($b,$cu_id,$message,$time);
    }

    //todo 消息推送等业务
    private function HeYueNext($data,$cu_id,$message,$time){     
      	return;
      	$msg =  $this->GetMessage($message['content'],$message['title'],$data);
      	if(!$msg)return;
        $map= ['cu_id'=>$cu_id,'time'=>$time];
        $user = Db::name('heyue_user')->where($map)->column('uid');
      	if(!$user)return;
        $res =  $this->SendMsg($msg,$user,6);
      	$reg_id = $this->GetPushReg($user);
      	if($reg_id)$this->PushMsg($msg['content'],$msg['title'],$reg_id);
    }

    private function tran($Close,$platform,$title,$time,$cu_id){
        $x = Db::name('price_set')->column('x');
        $baoz = ($Close*$x[0]-$Close)*$x[2]+$Close ;           //todo 暴涨
        $zuiz = ($Close *  $x[0] - $Close) * $x[3]+$Close;     //todo 最高
        $ciz  = $Close * $x[4];                                      //todo 次高
        $cid  = ($Close/$x[1] + $Close/$x[0])  * $x[5];	 				//todo 次低
        $zuid = $Close- ($Close -  $Close/$x[1])   * $x[6]; 			//todo 最低
        $baod = $Close- ($Close -  $Close/$x[1])   * $x[7];			 	//todo 暴跌
        $set = [
            'time'	=>		$time,
            'buy_1' =>      $this->ChangePrice($cid),
            'buy_2' =>      $this->ChangePrice($zuid),
            'buy_3' =>      $this->ChangePrice($baod),
            'sell_1'=>      $this->ChangePrice($ciz),
            'sell_2'=>      $this->ChangePrice($zuiz),
            'sell_3'=>      $this->ChangePrice($baoz),
            'platform'=>    $platform,
            'title'   =>    $title,
            'price'   =>    $Close,
          	'cu_id'	  =>	$cu_id,
        ];
        $id = Db::name('heyue_data')->where(['platform'=>$platform,'title'=>$title,'time'=>$time])->value('id');
        if(!$id){
            $res = Db::name('heyue_data')->insert($set);
        }else{
            $set['id'] = $id;
            $res = Db::name('heyue_data')->update($set);
        }
        return $set;
    }
}